package com.hj.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.hj.system.entity.base.DeptEntity;
import com.hj.system.entity.base.MenuEntity;
import com.hj.system.mapper.DeptMapper;
import com.hj.system.service.DeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * <p>
 * 部门管理 服务实现类
 * </p>
 *
 * @author wxf
 * @since 2021-04-01
 */
@Service
@Slf4j
public class DeptServiceImpl extends ServiceImpl<DeptMapper, DeptEntity> implements DeptService {

    @Override
    public boolean save(DeptEntity dept) {
        log.info("增加部门");
        Integer parentId = dept.getParentId();
        String p_queryCode = "0";
        if (parentId != 0) {
            DeptEntity parent = this.getById(parentId);
            p_queryCode = parent.getQueryCode();
        }
        //查询所有子节点
        List<DeptEntity> children = this.list(new QueryWrapper<DeptEntity>() {
        }.eq("parent_id", parentId));
        if (children.size() == 0) {
            dept.setQueryCode(p_queryCode + "-1");
        } else {
            Collections.sort(children, Comparator.comparingInt(o -> -Integer.valueOf(o.getDeptId())));
            DeptEntity lastChild = children.get(0);
            String c_queryCode = lastChild.getQueryCode();
            int length = c_queryCode.length();
            String prx = c_queryCode.substring(0, length - 1);
            String sub = c_queryCode.substring(length - 1, length);
            String n_queryCode = prx + (Integer.valueOf(sub) + 1);
            dept.setQueryCode(n_queryCode);
        }
        return SqlHelper.retBool(getBaseMapper().insert(dept));
    }

    @Override
    public boolean removeById(Serializable id) {
        DeptEntity deptEntity = this.getById(id);
        String queryCode = deptEntity.getQueryCode();
        return SqlHelper.retBool(getBaseMapper().delete(new QueryWrapper<DeptEntity>() {
        }.likeRight("query_code", queryCode)));
    }
}
